/**
 * 金币管理工具类
 * 提供金币相关的本地存储和操作方法
 */

class GoldManager {
  constructor() {
    this.storageKey = 'userGoldData'
  }

  /**
   * 检查用户是否已登录
   */
  isLoggedIn() {
    try {
      const token = uni.getStorageSync('user_token')
      return !!token
    } catch (error) {
      console.error('检查登录状态失败:', error)
      return false
    }
  }

  /**
   * 获取金币数据
   */
  getGoldData() {
    try {
      const data = uni.getStorageSync(this.storageKey)
      return data ? JSON.parse(data) : null
    } catch (error) {
      console.error('获取金币数据失败:', error)
      return null
    }
  }

  /**
   * 保存金币数据
   */
  saveGoldData(data) {
    try {
      uni.setStorageSync(this.storageKey, JSON.stringify(data))
      return true
    } catch (error) {
      console.error('保存金币数据失败:', error)
      return false
    }
  }

  /**
   * 获取当前金币数量
   */
  getCurrentGold() {
    const data = this.getGoldData()
    return data ? data.gold : 0
  }

  /**
   * 记录退出时间（用户退出登录时调用）
   */
  recordLogoutTime() {
    if (!this.isLoggedIn()) {
      return false
    }
    
    const currentData = this.getGoldData()
    if (currentData) {
      currentData.lastLogoutTime = new Date().toISOString()
      // 更新最后更新时间
      currentData.lastUpdateTime = new Date().toISOString()
      this.saveGoldData(currentData)
      console.log('已记录退出时间:', currentData.lastLogoutTime)
      return true
    }
    return false
  }

  /**
   * 计算离线收益（用户登录时调用）
   * @returns {Object} { offlineGold: 离线收益金币数, offlineSeconds: 离线秒数 }
   */
  calculateOfflineReward() {
    if (!this.isLoggedIn()) {
      return { offlineGold: 0, offlineSeconds: 0 }
    }

    const currentData = this.getGoldData()
    if (!currentData || !currentData.lastLogoutTime) {
      // 如果没有退出时间记录，可能是首次登录或数据异常
      return { offlineGold: 0, offlineSeconds: 0 }
    }

    const now = Date.now()
    const lastLogoutTime = new Date(currentData.lastLogoutTime).getTime()
    const offlineSeconds = Math.floor((now - lastLogoutTime) / 1000)

    // 计算离线收益（每秒1金币，最多24小时 = 86400秒）
    const maxOfflineSeconds = 86400 // 24小时
    const validOfflineSeconds = Math.min(offlineSeconds, maxOfflineSeconds)
    const offlineGold = validOfflineSeconds

    // 记录上线时间
    currentData.lastLoginTime = new Date().toISOString()
    currentData.lastUpdateTime = new Date().toISOString()
    // 清除退出时间
    delete currentData.lastLogoutTime
    this.saveGoldData(currentData)

    console.log(`离线收益计算: 离线${offlineSeconds}秒，获得${offlineGold}金币`)

    return {
      offlineGold,
      offlineSeconds,
      maxOfflineSeconds
    }
  }

  /**
   * 添加离线收益
   * @param {Number} offlineGold - 离线收益金币数
   * @returns {Boolean} 是否成功
   */
  addOfflineReward(offlineGold) {
    if (offlineGold <= 0) {
      return false
    }

    const currentData = this.getGoldData()
    if (!currentData) {
      // 如果没有数据，初始化
      const newData = {
        gold: offlineGold,
        recentActivities: [{
          id: Date.now(),
          icon: '💤',
          title: `离线收益 +${offlineGold}金币`,
          time: '刚刚',
          gold: offlineGold,
          type: 'earn'
        }],
        lastUpdateTime: new Date().toISOString()
      }
      return this.saveGoldData(newData)
    }

    const newGold = currentData.gold + offlineGold

    // 添加离线收益活动记录
    const newActivity = {
      id: Date.now(),
      icon: '💤',
      title: `离线收益 +${offlineGold}金币`,
      time: '刚刚',
      gold: offlineGold,
      type: 'earn'
    }

    const activities = currentData.recentActivities || []
    activities.unshift(newActivity)

    // 限制活动记录数量
    if (activities.length > 10) {
      activities.splice(10)
    }

    const newData = {
      ...currentData,
      gold: newGold,
      recentActivities: activities,
      lastUpdateTime: new Date().toISOString()
    }

    return this.saveGoldData(newData)
  }

  /**
   * 添加金币
   */
  addGold(gold, reason = '获得金币') {
    // 检查是否已登录
    if (!this.isLoggedIn()) {
      console.warn('未登录用户无法获得金币')
      return false
    }
    
    const currentData = this.getGoldData()
    if (!currentData) {
      // 初始化数据
      const newGold = gold
      const newData = {
        gold: newGold,
        recentActivities: [{
          id: Date.now(),
          icon: '💰',
          title: reason,
          time: '刚刚',
          gold: gold,
          type: 'earn'
        }]
      }
      this.saveGoldData(newData)
      return true
    }

    const newGold = currentData.gold + gold
    
    // 添加活动记录
    const newActivity = {
      id: Date.now(),
      icon: '💰',
      title: reason,
      time: '刚刚',
      gold: gold,
      type: 'earn'
    }
    
    const activities = currentData.recentActivities || []
    activities.unshift(newActivity)
    
    // 限制活动记录数量
    if (activities.length > 10) {
      activities.splice(10)
    }

    const newData = {
      ...currentData,
      gold: newGold,
      recentActivities: activities
    }

    return this.saveGoldData(newData)
  }

  /**
   * 消费金币
   */
  spendGold(gold, reason = '消费金币') {
    const currentData = this.getGoldData()
    if (!currentData) {
      console.warn('没有金币数据')
      return false
    }

    if (currentData.gold < gold) {
      console.warn('金币不足')
      return false
    }

    const newGold = currentData.gold - gold
    
    // 添加活动记录
    const newActivity = {
      id: Date.now(),
      icon: '💸',
      title: reason,
      time: '刚刚',
      gold: -gold,
      type: 'spend'
    }
    
    const activities = currentData.recentActivities || []
    activities.unshift(newActivity)
    
    // 限制活动记录数量
    if (activities.length > 10) {
      activities.splice(10)
    }

    const newData = {
      ...currentData,
      gold: newGold,
      recentActivities: activities
    }

    return this.saveGoldData(newData)
  }

  /**
   * 获取最近活动记录
   */
  getRecentActivities(limit = 10) {
    const data = this.getGoldData()
    if (!data || !data.recentActivities) {
      return []
    }
    return data.recentActivities.slice(0, limit)
  }

  /**
   * 初始化金币数据（用于新用户）
   */
  initGoldData(initialGold = 100) {
    const newData = {
      gold: initialGold,
      recentActivities: [{
        id: Date.now(),
        icon: '🎁',
        title: '新用户奖励',
        time: '刚刚',
        gold: initialGold,
        type: 'earn'
      }]
    }
    return this.saveGoldData(newData)
  }

  /**
   * 检查用户是否有足够的金币
   */
  hasEnoughGold(amount) {
    const currentGold = this.getCurrentGold()
    return currentGold >= amount
  }

  /**
   * 获取金币统计信息
   */
  getGoldStats() {
    const data = this.getGoldData()
    if (!data) {
      return {
        currentGold: 0,
        totalEarned: 0,
        totalSpent: 0,
        activityCount: 0
      }
    }

    const activities = data.recentActivities || []
    let totalEarned = 0
    let totalSpent = 0

    activities.forEach(activity => {
      if (activity.type === 'earn') {
        totalEarned += activity.gold
      } else if (activity.type === 'spend') {
        totalSpent += Math.abs(activity.gold)
      }
    })

    return {
      currentGold: data.gold,
      totalEarned: totalEarned,
      totalSpent: totalSpent,
      activityCount: activities.length
    }
  }
}

// 创建单例实例
const goldManager = new GoldManager()

export default goldManager
